//
//  InsuranceBrokersContentViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/1/17.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "InsuranceBrokersContentViewController.h"
#import "MyWebView.h"
#import "QuestionsView.h"
#import "V4ShareShowView.h"


@interface InsuranceBrokersContentViewController ()<UIWebViewDelegate,QuestionsViewDelegate>{
    MyWebView *WebView;
    NSString *strTempUrl;
    NSArray *arrayType;
    
//    NSString *strTitle;
//    NSString *strDescription;
//    NSString *strImageUrl;
    
    BOOL boolBack;
    
    BOOL boolRefresh;
    
    QuestionsView *qView;
    UIButton *btnCollection;
}

@end

@implementation InsuranceBrokersContentViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initComponents];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myWebView_nil:) name:@"myWebView_nil" object:nil];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (boolRefresh) {
        boolRefresh=NO;
        [WebView refreshWeb];
    }
    [SVProgressHUD dismiss];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [SVProgressHUD dismiss];
}

#pragma mark push_NSNotification
-(void)myWebView_nil:(NSNotification *)note{
    [WebView removeFromSuperview];
    WebView=nil;
}


- (void)initComponents{
    strTempUrl=@"";
    
//    [self rightButton:nil image:@"headfx" sel:@selector(rightBUttonClicked)];
//    self.navrightButton.frame=CGRectMake(kScreenWidth-44, 20, 44, 44);
//    btnCollection=[RHMethods buttonWithFrame:CGRectMake(kScreenWidth-88, 20, 44, 44) title:nil image:@"headsc" bgimage:nil];
//    [btnCollection setImage:[UIImage imageNamed:@"headscon"] forState:UIControlStateSelected];
//    [btnCollection addTarget:self action:@selector(collectionButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//    [self.navView addSubview:btnCollection];
//    btnCollection.selected=![[self.otherInfo valueForJSONStrKey:@"iscollection"] isEqualToString:@"0"];//iscollection        int            是否已收藏（0.未收藏 02.09新增）
    
    
//    arrayImages=[NSMutableArray new];
    [self rightButton:nil image:@"shareicon" sel:@selector(rightBUttonClicked)];
    self.navrightButton.frame=CGRectMake(kScreenWidth-44, 20, 44, 44);
    
    
    WebView = [[MyWebView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth,kContentHeight)];
    WebView.delegate=self;
    [self.view addSubview:WebView];
    WebView.scalesPageToFit=YES;
    [WebView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    strTempUrl=[self.otherInfo valueForJSONStrKey:@"url"];
    if (strTempUrl.length>4) {
        strTempUrl= [[[strTempUrl lowercaseString] substringToIndex:4] isEqualToString:@"http"]?strTempUrl:[NSString stringWithFormat:@"http://%@",strTempUrl];
    }
    
    [WebView loadMyWeb:strTempUrl];
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        WebView.frameHeight=kContentHeight-44;
        UIView *viewBottom=[[UIView alloc] initWithFrame:CGRectMake(0, YH(WebView), kScreenWidth, 44)];
        viewBottom.backgroundColor=RGBCOLOR(56, 58, 75);
        viewBottom.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
        [self.view addSubview:viewBottom];
        
        UIButton *btnLeft=[RHMethods buttonWithFrame:CGRectMake(0, 0, kScreenWidth/2, 44) title:@"  电话咨询" image:@"phoneicon070116" bgimage:nil];
        [btnLeft addTarget:self action:@selector(telButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [btnLeft setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [viewBottom addSubview:btnLeft];
        
        UIButton *btnRight=[RHMethods buttonWithFrame:CGRectMake(kScreenWidth/2, 0, kScreenWidth/2, 44) title:@"  在线提问" image:@"tiwenicon070116" bgimage:nil];
        [btnRight addTarget:self action:@selector(twButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [btnRight setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [viewBottom addSubview:btnRight];
        
        UIView *viewLine=[[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/2, 12, 1, 20)];
        viewLine.backgroundColor=[UIColor whiteColor];
        [viewBottom addSubview:viewLine];
    }
    
}
#pragma mark button
-(void)collectionButtonClicked{
    //收藏
    btnCollection.selected=!btnCollection.selected;
    NSString *urls=[NSString stringWithFormat:XKFnewscollection,[[Utility Share] userId],[[Utility Share] userToken],[self.otherInfo valueForJSONStrKey:@"id"],btnCollection.selected?@"1":@"0"];
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        urls=[NSString stringWithFormat:XKFV3homescollection,[[Utility Share] userId],[[Utility Share] userToken],[self.otherInfo valueForJSONStrKey:@"id"],btnCollection.selected?@"1":@"0"];
    }
    [NetEngine createGetAction_LJ:urls onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [self backRefreshData];
        }else{
            btnCollection.selected=!btnCollection.selected;
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
}
-(void)rightBUttonClicked{
    //分享
    /*
     {
     "src": "/upload/tumour/1/1478856592.jpg",
     "title": "出现肿瘤别慌",
     "descr": "出现肿瘤别慌",
     "url": "http://www.jiusheng.com/wappage/news_detail?id=1"
     }
     
     */
    NSDictionary *dct=[self.otherInfo objectForJSONKey:@"sharedata"];
    NSMutableDictionary *dic=[NSMutableDictionary new];
    [dic setValue:[dct valueForJSONStrKey:@"pic"] forKey:@"src"];
    [dic setValue:[dct valueForJSONStrKey:@"title"] forKey:@"title"];
    [dic setValue:[dct valueForJSONStrKey:@"content"] forKey:@"descr"];
    [dic setValue:[dct valueForJSONStrKey:@"url"] forKey:@"url"];
 
//    NSMutableDictionary*dictparam;
    
//    if ([self.userInfo isEqualToString:@"Insurance"]) {
//        
//        dictparam =[NSMutableDictionary new];
//        //        [dictparam setValue:@"1" forKey:@"type"];
//        [dictparam setObject:[NSString stringWithFormat:@"%@",[self.otherInfo valueForJSONStrKey:@"iscollection"]] forKey:@"iscollection"];
//        if (_Insurancedic) {
//            
//            [dictparam setObject:[NSString stringWithFormat:@"%@",[_Insurancedic valueForJSONStrKey:@"iscollection"]] forKey:@"iscollection"];
//        }
//        [dictparam setObject:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"id"];
//        //        [dictparam setObject:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"id"];
//        //        ![[self.otherInfo valueForJSONStrKey:@"iscollection"] isEqualToString:@"0"]
//    }else{
//        [dictparam setValue:@"2" forKey:@"type"];
//    }
//    [dictparam setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"objid"];
    
    
    [V4ShareShowView showMeWithShareDic:dic WithCollectiondic:nil CallBackBlock:^(id data, int status, NSString *msg) {
        if (status==200) {
            if ([data isEqualToString:@"收藏"]) {
                //                 [self backRefreshData];
                //                        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
                //                            [self backRefreshData];
                //                        }else{
                //                //            _btnCollection.selected=!_btnCollection.selected;
                ////                            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
                //                        }
            }else{
                
                [self shareStatistics];
            }
        }
        
    }];
    
//    [[Utility Share] showShareData:dic suc:^(NSInteger NoSuc) {
//        if (NoSuc==1) {
//            [SVProgressHUD showSuccessWithStatus:@"分享成功！"];
//            [self shareStatistics];
//        }
//    }];
}
-(void)shareStatistics{
    krequestParam
    if ([self.userInfo isEqualToString:@"Insurance"]) {
        [dictparam setValue:@"1" forKey:@"type"];
    }else{
        [dictparam setValue:@"2" forKey:@"type"];
    }
    [dictparam setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"objid"];
    [NetEngine createGetAction_LJ:[NSString stringWithFormat:@"%@%@",XKFV3usershare,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
//        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//            
//        }else{
//        }
    }];
}
-(void)telButtonClicked{
    DLog(@"\n\n\n拨号：%@\n\n\n",[self.otherInfo valueForJSONStrKey:@"telephone"]);
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSString *telUrl = [NSString stringWithFormat:@"tel:%@",[self.otherInfo valueForJSONStrKey:@"telephone"]];
    NSURL *telURL =[NSURL URLWithString:telUrl];// 貌似tel:// 或者 tel: 都行
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
}
-(void)twButtonClicked{
    //提问
    if (!qView) {
        qView=[[QuestionsView alloc] init];
    }
    qView.delegate=self;
    qView.memoDic=@{@"id":[self.otherInfo valueForJSONStrKey:@"id"]};
    [qView show];
}

//分离URL参数
-(NSMutableDictionary *)dicSeparatedUrl:(NSString *)strurl{
    //获取问号的位置，问号后是参数列表
    NSRange range = [strurl rangeOfString:@"?"];
    NSLog(@"参数列表开始的位置：%d", (int)range.location);
    
    //获取参数列表
    NSString *propertys = [strurl substringFromIndex:(int)(range.location+1)];
    NSLog(@"截取的参数列表：%@", propertys);
    
    //进行字符串的拆分，通过&来拆分，把每个参数分开
    NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
    NSLog(@"把每个参数列表进行拆分，返回为数组：n%@", subArray);
    
    //把subArray转换为字典
    //tempDic中存放一个URL中转换的键值对
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithCapacity:4];
    
    for (int j = 0 ; j < subArray.count; j++)
    {
        if ([subArray[j] notEmptyOrNull]) {
            //在通过=拆分键和值
            NSArray *dicArray = [subArray[j] componentsSeparatedByString:@"="];
            if ([dicArray count]>1) {
                //给字典加入元素
                [tempDic setObject:dicArray[1] forKey:dicArray[0]];
            }else if([dicArray count]){
                [tempDic setObject:@"" forKey:dicArray[0]];
            }
        }
    }
    NSLog(@"打印参数列表生成的字典：n%@", tempDic);
    
    return tempDic;
}
#pragma markUIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    strTempUrl= [request.URL absoluteString];
    DLog(@"request.URL:%@",strTempUrl);
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    //    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeNone];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
//    strDescription = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName(\"description\")[0].content"];
//    DLog(@"strDescription______:%@",strDescription);
//    strImageUrl= [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName(\"picture\")[0].content"];
//    DLog(@"strImageUrl______:%@",strImageUrl);
//
//    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
//    DLog(@"currentURL:%@",currentURL);
//    strTempUrl=currentURL;
//
//
//    NSString *elementsByName = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('share')[0].value"];
//    DLog(@"ElementsByName:%@",elementsByName);
//    if ([elementsByName notEmptyOrNull] && [elementsByName isEqualToString:@"1"]) {
//        self.navrightButton.hidden=NO;
//    }else{
//        self.navrightButton.hidden=YES;
//    }
//    
    NSString * strTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if ([strTitle notEmptyOrNull]) {
        [self navbarTitle:strTitle];
    }
    
    //    [SVProgressHUD dismiss];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    //    [SVProgressHUD showImage:nil status:@"加载失败,下拉可以刷新界面"];
    DLog(@"error:%@",error);
}
#pragma mark pop
-(void)popRefreshData{
    boolRefresh=YES;
}
#pragma mark QuestionsViewDelegate
-(void)QuestionsViewViewSubmint:(QuestionsView *)sview object:(id)dic{
    [WebView refreshWeb];
}


-(void)backRefreshData{
    for (id controller in self.navigationController.viewControllers) {
        if ([NSStringFromClass([controller class]) isEqualToString:@"LicensePlateViewController"]||
            [NSStringFromClass([controller class]) isEqualToString:@"UserLicensePlateViewController" ]||
            [NSStringFromClass([controller class]) isEqualToString:@"UserExtensionViewController" ]) {
            if ([(NSObject*)controller respondsToSelector:@selector(popRefreshData)]) {
                [controller performSelector:@selector(popRefreshData) withObject:nil afterDelay:0.01];
            }
            continue;
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
